<?php
declare (strict_types = 1);
namespace app\api\controller;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Iai\V20200303\IaiClient;

use TencentCloud\Iai\V20200303\Models\CreateGroupRequest;  /** 人员库 */
use TencentCloud\Iai\V20200303\Models\CreatePersonRequest;  /** 人员 */
use TencentCloud\Iai\V20200303\Models\SearchFacesRequest;  /** 人脸搜索 */
use TencentCloud\Iai\V20200303\Models\DeletePersonRequest;  /** 删除人员 */

use think\Request;
use think\Exception;
use app\BaseController;

use think\facade\{Log, Db};
use think\exception\ValidateException;

use app\api\validate\{UsersValidate};
use app\api\model\{Users};

class Face2Controller extends BaseController
{
    /** 创建人员库 */
    public function face_Group_add()
    {
        try {

            $cred = new Credential("AKIDPYWP2P6O1h9MSKtJ6ogTcaKq8KG2DmQs", "Ox73y42ta6J9qPmvxlMIrFd1B6k80e4L");
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("iai.tencentcloudapi.com");
              
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new IaiClient($cred, "ap-beijing", $clientProfile);
        
            $req = new CreateGroupRequest();
            
            $params = array(
                "Action"    => "CreateGroup",
                "Version"   => "2020-03-03",
                "Region"    => "ap-beijing",
                "GroupName" => 'face_meiye',
                "GroupId"   => 'face_meiye'
            );
            $req->fromJsonString(json_encode($params));
        
            $resp = $client->CreateGroup($req);

            /** 接收返回的数据并转数组 */
            $face_data = json_decode($resp->toJsonString(), true);

           $this->success_back('ok', $face_data);
        }
        catch(TencentCloudSDKException $e) {
            $this->error_back($e);
        }
    }

    /** 创建人员 */
    public function face_add(){
        $data = input('post.');
        $data['face'] = request()->file('face');

        try{
            validate(UsersValidate::class)->scene('face_add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel = new Users();

        /** 查询用户信息 */
        $user_info = $userModel->getFind(['id' => $data['user_id']]);

        if($user_info['code'] != 'ok'){
            $this->error_back('用户不存在或已删除');
        }

        try{
            $cred = new Credential("AKIDPYWP2P6O1h9MSKtJ6ogTcaKq8KG2DmQs", "Ox73y42ta6J9qPmvxlMIrFd1B6k80e4L");
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("iai.tencentcloudapi.com");
            
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new IaiClient($cred, "ap-beijing", $clientProfile);

            $req = new CreatePersonRequest();
            
            $params = array(
                "Action"     => "CreatePerson",
                "Version"    => "2020-03-03",
                "Region"     => "ap-beijing",
                "GroupId"    => 'face_meiye',
                "PersonName" => 'MY-' . $user_info['data']['id'],
                "PersonId"   => (string)$user_info['data']['id'],
                "Url"        => config('app.url') . fileUp($data['face'], 'face_group'),
            );

            $req->fromJsonString(json_encode($params));

            $resp = $client->CreatePerson($req);

            /** 接收返回的数据并转数组 */
            $face_data = json_decode($resp->toJsonString(), true);

            /** 修改用户录入人脸状态 */
            Db::name('users')->where(['id' => $data['user_id']])->update(['face' => 1]);

           $this->success_back('ok', $face_data);
        }catch(TencentCloudSDKException $e){
            $this->error_back($e);
        }
    }

    /** 删除人员 */
    public function face_del(){
        $data = input('post.');

        try{
            $cred = new Credential("AKIDPYWP2P6O1h9MSKtJ6ogTcaKq8KG2DmQs", "Ox73y42ta6J9qPmvxlMIrFd1B6k80e4L");
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("iai.tencentcloudapi.com");
            
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new IaiClient($cred, "ap-beijing", $clientProfile);

            $req = new DeletePersonRequest();
            
            $params = array(
                "Action"     => "DeletePerson",
                "Version"    => "2020-03-03",
                "Region"     => "ap-beijing",
                "GroupId"    => 'face_meiye',
                "PersonId"   => (string)$data['user_id'],
            );

            $req->fromJsonString(json_encode($params));

            $resp = $client->DeletePerson($req);

            /** 接收返回的数据并转数组 */
            $face_data = json_decode($resp->toJsonString(), true);

            /** 修改用户录入人脸状态 */
            Db::name('users')->where(['id' => $data['user_id']])->update(['face' => 0]);

           $this->success_back('ok', $face_data);
        }catch(TencentCloudSDKException $e){
            $this->error_back($e);
        }
    }

    /** 人脸搜索 */
    public function face_search(){
        $data['face'] = request()->file('face');

        try{
            validate(UsersValidate::class)->scene('face')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        try{
            $cred = new Credential("AKIDPYWP2P6O1h9MSKtJ6ogTcaKq8KG2DmQs", "Ox73y42ta6J9qPmvxlMIrFd1B6k80e4L");
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("iai.tencentcloudapi.com");
            
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new IaiClient($cred, "ap-beijing", $clientProfile);

            $req = new SearchFacesRequest();
            
            $params = array(
                "Action"     => "SearchFaces",
                "Version"    => "2020-03-03",
                "Region"     => "ap-beijing",
                "GroupIds"   => ['face_meiye'],
                "Url"        => config('app.url') . fileUp($data['face'], 'face_group_check'),
            );

            $req->fromJsonString(json_encode($params));

            $resp = $client->SearchFaces($req);

            /** 接收返回的数据并转数组 */
            $face_data = json_decode($resp->toJsonString(), true);

            if($face_data['Results'][0]['RetCode'] != 0){
                $this->error_back('图片质量不合格');
            }

            if(!$face_data['Results'][0]['Candidates']){
                $this->error_back('用户不存在');
            }

            /** 搜索结果 */
            $user_face_list = $face_data['Results'][0]['Candidates'];

            /** 80分及以上才认为是同一人 */
            if($user_face_list[0]['Score'] < 80){
                $this->error_back('用户不存在');
            }

            $this->success_back('ok', (int)$user_face_list[0]['PersonId']);
        }catch(TencentCloudSDKException $e){
            $this->error_back($e);
        }
    }

    /** 小程序端是否开启人脸 */
    public function is_face(){
        $info = Db::name('system')->where(['id' => 1])->find();

        $this->success_back('ok', $info['is_face']);
    }
}